﻿using Microsoft.AspNetCore.Http;
using Qiniu.Storage;
using Qiniu.Util;
using Qiniu.Http;


namespace B.S.BasicData.Api.Services
{
    public class QiniuUploadService
    {
        private readonly QiniuConfig _config;

        public QiniuUploadService(QiniuConfig config)
        {
            _config = config;
        }

        public async Task<string> UploadImageAsync(IFormFile file)
        {
            var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
            using var stream = file.OpenReadStream();
            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);
            var data = ms.ToArray();

            var putPolicy = new PutPolicy { Scope = _config.Bucket };
            var mac = new Mac(_config.AccessKey, _config.SecretKey);
            var token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            // 区域选择
            Zone zone = _config.Zone switch
            {
                "z0" => Zone.ZONE_CN_East,
                "z1" => Zone.ZONE_CN_North,
                "z2" => Zone.ZONE_CN_South,
                "na0" => Zone.ZONE_US_North,
                "as0" => Zone.ZONE_AS_Singapore,
                _ => Zone.ZONE_CN_East
            };
            var cfg = new Config { Zone = zone, UseHttps = true };
            var um = new UploadManager(cfg);

            var result = await Task.Run(() => um.UploadData(data, fileName, token, new PutExtra()));

            if (result.Code == 200)
                return $"{_config.Domain}/{fileName}";
            else
                throw new Exception(result.Text);
        }


        public async Task<List<string>> UploadImagesAsync(List<IFormFile> files)
        {
            var urls = new List<string>();
            foreach (var file in files)
            {
                if (file != null && file.Length > 0)
                {
                    var url = await UploadImageAsync(file);
                    urls.Add(url);
                }
            }
            return urls;
        }

        /// <summary>
        /// 删除七牛云上的文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>删除结果</returns>
        public async Task<bool> DeleteFileAsync(string fileName)
        {
            try
            {
                var mac = new Mac(_config.AccessKey, _config.SecretKey);

                // 区域选择
                Zone zone = _config.Zone switch
                {
                    "z0" => Zone.ZONE_CN_East,
                    "z1" => Zone.ZONE_CN_North,
                    "z2" => Zone.ZONE_CN_South,
                    "na0" => Zone.ZONE_US_North,
                    "as0" => Zone.ZONE_AS_Singapore,
                    _ => Zone.ZONE_CN_East
                };
                var cfg = new Config { Zone = zone, UseHttps = true };

                var bucketManager = new BucketManager(mac, cfg);

                var result = await Task.Run(() => bucketManager.Delete(_config.Bucket, fileName));
                
                return result.Code == 200;
            }
            catch (Exception)
            {
                return false;
            }
        }


    }
}